define(['jquery', 'select2','datetimepicker','mapController',"controller","coordtransform","rights","select2","moment","validate","mapview"], function ($) {

    var c = require("controller");
    var rights = require("rights");
    var mapController = require("mapController");
    var coordtransform = require("coordtransform");
    var tHeight = $(window).height() - 50 - 35;
    var moment=require("moment");
    var mapview = require("mapview");
    //获取公司
    var Companys=c.getAllCompanys();
    var nn=[];//公司临时数组
    $.each(Companys,function (i,v) {
        nn.push({id:v.cid,text:v.name})
    });

    $(".content").height(tHeight);
    return {
        init: function () {
            // test set token
            // localStorage.setItem('token', 'MiMxNDcyNjk0Mjk4QGcuZmx5LWNsb3VkLmNuI1pjZDYzQ2tqeXg1MzdHSkRQWU43SEkxUS9Ecz0=');
            this.searchData={};
            this.initDataTable();
            this.bindEvent();
        },
        dataTable: null,
        delRow:null,
        searchData:{},
        initDataTable: function () {
            //获取公司
            $("#companys").select2({
                data:nn
            });
            var self = this;
            this.dataTable = c.myDataTable($("#mmg"), {
                ajax: function (data, callback, settings) {
                    //封装请求参数
                    var param = {
                        page_no: (data.start / data.length),
                        page_size: data.length
                    };
                    $.extend(true,param,self.searchData);
                    //ajax请求数据
                    c.ajax({
                        url: "spaceline/search",
                        cache: false, //禁用缓存
                        data: param, //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //封装返回数据
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.spacelines;//返回的数据列表
                            //console.log(returnData);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);
                        }
                    });
                },
                scrollY: (tHeight - 210) + "px",
                scrollCollapse: true,
                columns: [
                    {"data": "id"},
                    {"data": "name"},
                    {"data": "cid"},
                    {"data": "elements"},
                    {"data": "elements"},
                    {"data": "property"}
                ],
                columnDefs: [
                    {
                        "targets": 2,//所在公司列
                        "data": "cid",
                        "render": function (data, type, row) {
                            return c.getCompanys(row.cid);
                        }
                    },

                    {
                        "targets":3,//起降场
                        "data": "elements",
                        "render": function (data, type, row) {
                            var heliport = JSON.parse(row.elements);
                            var result='';
                            for(var i=0;i<heliport.length;i++){
                                var each = heliport[i];
                                if(each.type == 0){
                                    var property = JSON.parse(each.property);
                                    result += each.name+' ('+property.path[0].name+' '+property.path[0].lng+' , '+property.path[0].lat+')';
                                    if (i<heliport.length-1) {
                                        result += '<br/>'
                                    }
                                }
                            }
                            return result;
                        }
                    },
                    {
                        "targets":4,//航线或空域
                        "data": "elements",
                        "render": function (data, type, row) {
                            var details = JSON.parse(row.elements);
                            var result='';
                            for(var step in details){
                                var detail = details[step];
                                var property = JSON.parse(detail.property);
                                if(detail.type==253){
                                    result += detail.name + ' ('+property.path[0].name+ ' '+property.path[0].lng+' , '+property.path[0].lat+')<br/>'+'半径:'+property.radius+'M'+'<br/>';
                                }else if(detail.type==254 || detail.type==252 || detail.type==255){
                                    var paths = property.path;
                                    if(detail.type==255){
                                        result += paths.length+'点连线范围内'+(detail.ftype==1?'转场':'本场')+':<br/>';
                                    }else if(detail.type==254){
                                        result += paths.length+'点航线'+(detail.ftype==1?'转场':'本场')+':<br/>';
                                    }else if(detail.type==252){
                                        result += paths.length+'点往返'+(detail.ftype==1?'转场':'本场')+':<br/>';
                                    }
                                    var COUNTS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                                    $.each(paths, function (i) {
                                        var each = paths[i];
                                        result += COUNTS.substr(i,1)+' ('+each.name+' '+each.lng+' , '+each.lat+')<br/>';
                                    });
                                }else if(detail.type==1){
                                    result += detail.name+'途经点:<br/>' + property.path[0].lng+' , '+property.path[0].lat + '<br />';
                                }else if(detail.type==2){
                                    result += detail.name+'加油点:<br/>' + property.path[0].lng+' , '+property.path[0].lat + '<br />';
                                }else if(detail.type==3){
                                    result += detail.name+'机场:<br/>' + property.path[0].lng+' , '+property.path[0].lat + '<br />';
                                }

                            }
                            return result;
                        }
                    },
                    {
                        // 定义操作列,######以下是重点########
                        "targets": 5,//操作按钮目标列
                        "data": null,
                        "render": function (data, type, row) {
                            var html = "<div class='btn-group'>" +
                                "<a href='#' class='btn btn-sm btn-info edit' data-toggle='modal' data-target='#myModal' data-rights='4004'><i class='fa fa-edit'></i>编辑</a>" +
                                "<a href='#' class='btn btn-sm btn-danger' data-rights='4005'><i class='fa fa-remove'></i>删除</a>" +
                                "<a href='#' class='btn btn-sm btn-vk view' data-toggle='modal' data-target='#myModal' data-rights='4002'><i class='fa fa-eye'></i>查看</a>" +
                                "</div>";
                            return html;
                        }
                    }],
                    drawCallback: function(settings, json) {
                        rights.isShowFn($('.content'));
                    }
            });
        },
        bindEvent: function () {
            var self = this;
            $('#map').on('click', function () {
                //地图
                $("#myModal>.modal-dialog").load("spaceline/form.html", function(){
                    self.formInit()
                });
            });
            $('#add').on('click', function () {
                //添加
                $("#myModal>.modal-dialog").load("spaceline/form.html", function(){
                    self.formInit()
                });
            });
            $('#mmg').on('click', '.edit', function () {
                //编辑
                var dataRow = self.dataTable.row($(this).parents('tr')).data();
                $("#myModal>.modal-dialog").load("spaceline/form.html", function () {
                    self.formInit(dataRow)
                });
            }).on('click', '.view', function () {
                //查看
                var dataRow = self.dataTable.row($(this).parents('tr')).data();
                $("#myModal>.modal-dialog").load("spaceline/view.html", function () {
                    self.viewInit(dataRow);

                });
            }).on('click', '.btn-danger', function () {
                //删除
                var dataRow = self.dataTable.row($(this).parents('tr')).data();
                c.confirm({
                    content: "是否删除",
                    confirm: function () {
                        c.ajax({
                                url: "spaceline/delete",
                                data: {
                                    cid: dataRow.cid,
                                    id: dataRow.id
                                },
                                //headers:{"Access-Control-Allow-Origin":"*"},
                                success: function (res) {
                                    if (res.err < 0) {
                                        alert(res.msg);
                                        return
                                    }
                                    self.dataTable.ajax.reload();
                                    /*self.dataTable.row($('.J_remove'))
                                     .remove().draw();*/
                                }
                            }
                        )
                    }
                })
            })
                .on('click', 'tr', function () {
                    $(this).siblings().removeClass("select");
                    $(this).toggleClass("select");
                });
            $('#search').on('click', function () {
                self.searchData = {

                };
                var cid = $('#companys').val();
                var name = $('#searchName').val();
                if(name!=''){
                    self.searchData.name = name
                }
                if(cid!=''){
                    self.searchData.cid = cid
                }
                self.dataTable.draw();
            });

            $('[name="role"]').on('change', function () {
                if ($('[name="role"]').val() === "CORP") {
                    $(".company").removeClass('hide');
                } else {
                    $(".company").addClass('hide');
                }
            });

            $('.search-input').on('keyup', function () {
                console.log(this.value);
                // self.dataTable.search(this.value, false, false).draw();
            })

        },
        formInit:function (dataRow,isView) {
            var self=this;

            //获取公司
            $("#companys2").select2({
                data:nn
            });
            var form_elementData=[];
            var $form = $('.edit-form');
            /*$('#expire').datepicker({
                language: 'zh-CN',
                format: 'yyyy-mm-dd',
                autoclose: true,
                startDate:moment().add(1, 'days').format('YYYY-MM-DD')
            });*/
            $('#expire').datetimepicker({
                locale: 'zh-CN',
                format: 'YYYY-MM-DD',
                minDate:moment().add(1, 'days').format('YYYY-MM-DD')
            });



            $("#cid").select2();
            $("#cid").on("change", function (e) {
                form_elementData=[];
            });
            if(dataRow){//判断是否编辑

                $form.find('[name="id"]').val(dataRow.id);
                $form.find('[name="cid"]').val(dataRow.cid).trigger('change').attr('readonly',true);
                $form.find('[name="expire"]').val(moment(dataRow.expire*1000).format('YYYY-MM-DD'));
                $form.find('[name="name"]').val(dataRow.name);
                //$form.find('[name="did"]').val(dataRow.did);
                form_elementData=JSON.parse(dataRow.elements);
                $('#myModal').find('.modal-title').text('编辑空域航线');

            }

            if(isView){
                $('#add_element').hide();
                $('.submit-btn',$('#myModal')).hide();
            }



            var form_element = c.myDataTable($("#form_element"), {
                aaData:form_elementData,
                scrollY: (200) + "px",
                scrollCollapse: true,
                "processing": false,
                "serverSide": false,
                paging:false,
                info:false,
                columns: [
                    {"data": "name"},
                    {
                        "data": "type",
                        "render": function (data, type, row) {
                            if(data!=252){
                                return c.getElementType(data);
                            }else{
                                return "往返";
                            }

                        }
                    },
                    {
                        "data": "type",
                        "render": function (data, type, row) {
                            if(data==253||data==254||data==255){
                                if(row.ftype==0){
                                    return "本场";
                                }else{
                                    return "转场";
                                }
                            }else{
                                return ""
                            }
                        }
                    },
                    /*{
                        //详情信息
                        "data": "property",
                        "render": function (data, type, row) {
                            var result = '';
                            var tempParam = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                            var property = row.property;
                            property = JSON.parse(property);
                            if (row.type == 0) {
                                result = row.name + ' ( ' + property.path[0].name + ': ' + property.path[0].lng + ' , ' + property.path[0].lat + ' )';
                            } else if (row.type == 253) {
                                result = row.name + ' ( '
                                    + property.path[0].name + ': ' + property.path[0].lng + ' , ' + property.path[0].lat + ' )'
                                    + ' )<br>(半径:' + property.radius + '米)';
                            } else {
                                $.each(property.path, function (i) {
                                    result += tempParam.substring(i, i + 1)
                                        + ' ( ' + property.path[i].name + ': ' + property.path[i].lng + ' , ' + property.path[i].lat + ' )<br>';
                                });
                            }
                            return result;

                        }
                    },*/
                    {
                        // 定义操作列,######以下是重点########
                        "data": null,
                        "render": function (data, type, row) {
                            var html = "<div class='btn-group'>" +
                                "<a href='#' class='btn btn-sm btn-danger removeButton'><i class='fa fa-remove'></i>删除</a>" +
                                //"<a href='#' class='btn btn-sm btn-info edit' data-toggle='modal' data-target='#myModal' data-rights='4002'><i class='fa fa-eye'></i>查看</a>" +
                                "</div>";
                            return isView?"":html;
                        }
                    }
                ]
                // drawCallback: function(settings, json) {
                //     rights.isShowFn($('.content'));
                // }
            });
            //添加飞行要素
            $('#add_element').on('click',function () {

                $("#elementsModal>.modal-dialog").load("spaceline/elements.html", function(){
                    $("#elementsModal").modal("show");
                    self.formElementsInit($("#cid").val(),form_element,form_elementData);
                });
            });
            //地图展示飞行要素
            $('#show_element').on('click',function () {
                $("#mapModal>.modal-dialog").load("element/mapview.html", function(){
                    $("#mapModal").modal("show");
                    mapview.init(form_elementData);
                });
            });

            $("#form_element").on('click','.removeButton',function () {//飞行要素移除
                var row = form_element.row( $(this).parents('tr') );
                var index = row.index();
                form_elementData.splice(index,1);
                row.remove().draw();
            });
            //form_form_element.rows.add(json).draw();
            //提交

            $('.edit-form').validate({
                submitHandler: function (form) {
                    var mode = $('#myModal').find('.modal-title').text();
                    /*var formData = new FormData($('.edit-form').get(0));
                     // 时间回转
                     var fdata =  Date.parse(formData.get('factory_time')) / 1000;*/
                    var params = {
                    };
                    $.each($('.edit-form').serializeArray(),function (i,el) {
                        params[el.name]=el.value;
                    });


                    // if(params.name==""){
                    //     c.alert({
                    //         content:'请填写名称'
                    //     });
                    //     return false;
                    // }

                    if(params.expire==""){
                        c.alert({
                            content:'请填写有效日期'
                        });
                        return false;
                    }else{
                        params.expire=moment(params.expire).unix();
                    }


                    if(form_elementData.length==0){
                        c.alert({
                            content:'请填加飞行要素'
                        });
                        return false;
                    }else{
                        params.elements=JSON.stringify(form_elementData).replace(/"type"/gm,'"etype"');
                        if(params.elements.indexOf('"etype":0') ==-1 || !(params.elements.indexOf('"etype":252')>0||params.elements.indexOf('"etype":253')>0||params.elements.indexOf('"etype":254')>0||params.elements.indexOf('"etype":255')>0) ){
                            c.alert({
                                content:'飞行要素中起降点和空域为必选'
                            });
                            return false;
                        }
                    }

                    var url='spaceline/';
                    if (mode === "创建空域航线") {
                        url+= 'create';
                    } else {
                        url  += 'update';
                    }
                    c.ajax({
                        url: url,
                        dataType: "json",
                        cache: false,
                        data: params,
                        success: function (res) {
                            $('#myModal').modal('hide');
                    if (res.err < 0) {
                        return;
                    }
                    self.dataTable.ajax.reload();
                }
                    });


                }
            })
        },
        viewInit:function (dataRow,isView) {
            var self=this;
            var $form = $('.edit-form');
            //获取公司

            if(dataRow){//判断是否编辑

                $form.find('[name="id"]').val(dataRow.id);
                $form.find('[name="cid"]').val(c.getCompanys(dataRow.cid));
                $form.find('[name="expire"]').val(moment(dataRow.expire*1000).format('YYYY-MM-DD'));
                $form.find('[name="name"]').val(dataRow.name);
                //$form.find('[name="did"]').val(dataRow.did);
                var form_elementData=JSON.parse(dataRow.elements);

            }





            var form_element = c.myDataTable($("#form_element"), {
                aaData:form_elementData,
                scrollY: (300) + "px",
                scrollCollapse: true,
                "processing": false,
                "serverSide": false,
                paging:false,
                info:false,
                columns: [
                    {"data": "name"},
                    {
                        "data": "type",
                        "render": function (data, type, row) {
                            if(data!=252){
                                return c.getElementType(data);
                            }else{
                                return "往返";
                            }

                        }
                    },
                    {
                        "data": "type",
                        "render": function (data, type, row) {
                            if(data==253||data==254||data==255){
                                if(row.ftype==0){
                                    return "本场";
                                }else{
                                    return "转场";
                                }
                            }else{
                                return ""
                            }
                        }
                    },
                    {
                        //详情信息
                        "data": "property",
                        "render": function (data, type, row) {
                            var result = '';
                            var tempParam = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                            var property = row.property;
                            property = JSON.parse(property);
                            if (row.type == 0) {
                                result = row.name + ' ( ' + property.path[0].name + ': ' + property.path[0].lng + ' , ' + property.path[0].lat + ' )';
                            } else if (row.type == 253) {
                                result = row.name + ' ( '
                                    + property.path[0].name + ': ' + property.path[0].lng + ' , ' + property.path[0].lat + ' )'
                                    + ' )<br>(半径:' + property.radius + '米)';
                            } else {
                                $.each(property.path, function (i) {
                                    result += tempParam.substring(i, i + 1)
                                        + ' ( ' + property.path[i].name + ': ' + property.path[i].lng + ' , ' + property.path[i].lat + ' )<br>';
                                });
                            }
                            return result;

                        }
                    }
                ]
                // drawCallback: function(settings, json) {
                //     rights.isShowFn($('.content'));
                // }
            });

            //地图展示飞行要素
            $('#show_element').on('click',function () {
                $("#mapModal>.modal-dialog").load("element/mapview.html", function(){
                    $("#mapModal").modal("show");
                    mapview.init(form_elementData);
                });
            });


        },
        formElementsInit:function (cid,form_element,form_elementData) {

            var searchData={};
            var elements= c.myDataTable($("#elements"), {
                ajax: function (data, callback, settings) {
                    //封装请求参数
                    var param = {
                        page_no: (data.start / data.length),
                        page_size: data.length,
                        cid:cid
                    };
                    $.extend(true, param, searchData);
                    //ajax请求数据
                    c.ajax({
                        url: "element/search",
                        cache: false, //禁用缓存
                        data: param, //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //封装返回数据
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.elements;//返回的数据列表
                            //console.log(returnData);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);
                        }
                    });
                },
                scrollY: (200) + "px",
                scrollCollapse: true,
                columns: [
                    {
                        "sClass": "text-center",
                        "data": "id",
                        "render": function (data, type, full, meta) {
                            var isChecked="";
                            $.each(form_elementData,function (i,rowdata) {
                                if(data==rowdata.id){
                                    isChecked='checked';
                                    return false;
                                }
                            });
                            return '<input type="checkbox"  class="checkchild" '+isChecked+' value="' + data + '" />';
                        },
                        "bSortable": false
                    },
                    {"data": "name"},
                    {
                        "data": "type",
                        "render": function (data, type, row) {
                            if(data!=254&&data!=252){
                                return c.getElementType(data);
                            }else{
                                var isChecked="";
                                $.each(form_elementData,function (i,rowdata) {
                                    if(row.id==rowdata.id&&rowdata.type==252){
                                        isChecked='selected';
                                        return false;
                                    }
                                });
                                var html = '<select class="hangxian"><option value="254">航线</option><option '+isChecked+' value="252">往返</option></select>';
                                return html;
                            }

                        }
                    },
                    {
                        "data": "type",
                        "render": function (data, type, row) {

                            if(data==253||data==254||data==255){
                                var isChecked="";
                                $.each(form_elementData,function (i,rowdata) {
                                    if(row.id==rowdata.id&&rowdata.ftype==1){
                                        isChecked='selected';
                                        return false;
                                    }
                                });
                                var html='<select class="ftype"><option value="0">本场</option><option value="1" '+isChecked+'>转场</option></select>';
                                return html;
                            }else{
                                return "";
                            }
                        }
                    },
                    {
                        //详情信息
                        "data": "property",
                        "render": function (data, type, row) {
                            var result = '';
                            var tempParam = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                            var property = row.property;
                            property = JSON.parse(property);
                            if (row.type == 0) {
                                result = row.name + ' ( ' + property.path[0].name + ': ' + property.path[0].lng + ' , ' + property.path[0].lat + ' )';
                            } else if (row.type == 253) {
                                result = row.name + ' ( '
                                    + property.path[0].name + ': ' + property.path[0].lng + ' , ' + property.path[0].lat + ' )'
                                    + ' )<br>(半径:' + property.radius + '米)';
                            } else {
                                $.each(property.path, function (i) {
                                    result += tempParam.substring(i, i + 1)
                                        + ' ( ' + property.path[i].name + ': ' + property.path[i].lng + ' , ' + property.path[i].lat + ' )<br>';
                                });
                            }
                            return result;

                        }
                    }
                ]
            });


            $('#elementsSearch').on('click',function (e) {
                searchData={
                    etype:$('#etype').val()=='all'?'0,1,2,3,253,254,255':$('#etype').val(),
                    name:$('#eName').val()
                };
                elements.draw();
            });

            $('#elements').on('change','.checkchild,select',function (e) {
                var f=$(this).parents('tr').find('.checkchild').is(':checked');
                var dataRow = elements.row( $(this).parents('tr') ).data();
                var type=dataRow.type;
                // dataRow.ftype=0
                if(type==253||type==254||type==255){
                    dataRow.ftype= $(this).parents('tr').find('select.ftype').val();
                }
                if(type==254){
                    dataRow.type= $(this).parents('tr').find('select.hangxian').val();
                }
                var isIn=false;
                $.each(form_elementData,function (i,row) {
                    if(row.id==dataRow.id){
                        if(f){
                            form_elementData[i]=dataRow;
                        }else{
                            form_elementData.splice(i,1);
                        }
                        isIn=true;
                        return false;
                    }
                });
                if(!isIn){
                    form_elementData.push(dataRow);
                }


            });

            $('#elements_button').on('click',function (e) {
                form_element.clear().rows.add(form_elementData).draw();
                $("#elementsModal").modal("hide");
            })

        },
        mapformInit:function (form_elementData) {
            $('#container').height($('#mapModal .modal-dialog').height()-$('#mapModal .modal-header').height()-$('#mapModal .modal-footer').height()-50);
            var map = mapController.initMap();
            map.init('container');

            $.each(form_elementData,function (i,point) {
                var space;
                var property =JSON.parse(point.property);
                $.each(property.path,function (i,v) {
                    var gj= coordtransform.wgs84togcj02(mapController.changeDMSToLng(v.lng),mapController.changeDMSToLat(v.lat));
                    v.lng=gj[0];
                    v.lat=gj[1];
                });
                var html='<li><span>'+(point.type==252?'往返':c.getElementType(point.type))+':'+point.name+'</span></li>';
                $('.ele-location').append(html);
                switch(point.type.toString())
                {
                    case "252":
                    case "254": //画航线

                        space=map.createPolyline(property.path,{
                            strokeColor: '#e63f00',
                            strokeOpacity: 1,
                            strokeWeight: 3,
                            zIndex:10,
                            title:point.name,
                            strokeStyle: "solid"
                        });

                        break;
                    case "255": // 多边形空域
                        space=map.createPolygon(property.path,{
                            fillColor:'#289BEC',
                            fillOpacity:0.4,
                            strokeColor:'#40A4FB',
                            zIndex:10,
                            title:point.name,
                            strokeWeight:2
                        });
                        break;
                    case "253":// 圆形空域
                        space=map.createCircle(property.path,{
                            fillColor:'#289BEC',
                            fillOpacity:0.4,
                            strokeColor:'#40A4FB',
                            zIndex:10,
                            radius:point.radius*1,
                            title:point.name,
                            strokeWeight:2
                        });
                        break;
                    case "0"://起降点
                        space=map.createMark({lnglat:property.path[0],title:point.name});
                        space.setIcon('../../images/marker_smart_packing.png',[16,16]);
                        break;
                    case "1"://途径点
                        space=map.createMark({lnglat:property.path[0],title:point.name});
                        space.setIcon('../../images/marker_smart_packing.png',[16,16]);
                        break;
                    case "2"://加油咪
                        space=map.createMark({lnglat:property.path[0],title:point.name});
                        space.setIcon('../../images/marker_smart_packing.png',[16,16]);
                        break;
                    case '3'://机场
                        space=map.createMark({lnglat:property.path[0],title:point.name});
                        space.setIcon('../../images/airport.png',[16,16]);

                        break;
                }
                map.addOverlay(space);

            })
        }
    }
});



